package com.ezops.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.shiro.authc.credential.DefaultPasswordService;
import org.apache.shiro.authc.credential.PasswordService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.ezops.dao.facade.DataTransferFacade;
import com.ezops.dao.facade.IClientDataTransferFacade;
import com.ezops.dao.facade.IReportDataTransferFacade;
import com.ezops.dao.generics.search.Search;
import com.ezops.models.Client;
import com.ezops.models.Group;
import com.ezops.models.Manager;
import com.ezops.models.Report;
import com.ezops.models.Resource;
import com.ezops.models.User;
import com.ezops.models.UserGroup;
import com.ezops.models.UserPreference;
import com.fasterxml.jackson.databind.ObjectMapper;

@Controller
public class SessionManagementController {

	final static Logger logger = LoggerFactory
			.getLogger(SessionManagementController.class);

	@Autowired
	@Qualifier("UserDataTransferFacade")
	private DataTransferFacade<User> userFacade;

	@Autowired
	private IClientDataTransferFacade clientFacade;

	@Autowired()
	@Qualifier("ManagerDataTransferFacade")
	private DataTransferFacade<Manager> managerFacade;

	@Autowired
	@Qualifier("GroupDataTransferFacade")
	private DataTransferFacade<Group> groupFacade;

	@Autowired
	@Qualifier("ResourceDataTransferFacade")
	private DataTransferFacade<Resource> resourceFacade;

	@Autowired
	@Qualifier("UserGroupDataTransferFacade")
	private DataTransferFacade<UserGroup> userGroupFacade;

	@Autowired
	private IReportDataTransferFacade reportFacade;

	@Autowired
	@Qualifier("UserPreferenceDataTransferFacade")
	private DataTransferFacade<UserPreference> userPrefFacade;

	/**
	 * User Login
	 * 
	 * @param jsonbody
	 * @param request
	 * @param response
	 * @return
	 */

	/**
	 * Get User
	 * 
	 * @param jsonbody
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/getUser/{userid}")
	@ResponseBody
	public String getUser(@RequestBody String jsonbody,
			@PathVariable("userid") String userId, HttpServletRequest request,
			HttpServletResponse response) {

		String jsonText = "";

		try {

			logger.debug("User JSON :      \n" + jsonbody);

			// Finds the user by id
			Search searchCriteria = new Search();
			searchCriteria.addFilterEqual("userId", userId);
			User foundUser = userFacade.searchUnique(searchCriteria);
			if (foundUser == null) {
				response.sendError(HttpServletResponse.SC_BAD_REQUEST,
						"User Not Found id[ " + userId + "]");
				return "";
			}

			ObjectMapper mapper = new ObjectMapper();
			jsonText = mapper.writeValueAsString(foundUser);

			response.setStatus(HttpServletResponse.SC_OK);
			response.setContentType("application/json");

			// Check that the passwords match

		} catch (Throwable e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			jsonText = "{\"ERROR_CODE\":\"" + e.getMessage() + "\"}";
			// Set the exception and send it back to the caller

		} finally {
		}

		return jsonText;
	}

	/**
	 * Get User
	 * 
	 * @param jsonbody
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/getAllUsers")
	@ResponseBody
	public String getAllUsers(HttpServletRequest request,
			HttpServletResponse response) {

		String jsonText = "";

		try {

			// Finds all users
			List<User> allUsers = userFacade.findAll();

			ObjectMapper mapper = new ObjectMapper();
			jsonText = mapper.writeValueAsString(allUsers);

			response.setStatus(HttpServletResponse.SC_OK);
			response.setContentType("application/json");

			// Check that the passwords match

		} catch (Throwable e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			jsonText = "{\"ERROR_CODE\":\"" + e.getMessage() + "\"}";
			// Set the exception and send it back to the caller

		} finally {
		}

		return jsonText;
	}

	/**
	 * Get Clients
	 * 
	 * @param jsonbody
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/getAllClients")
	@ResponseBody
	public String getAllClients(HttpServletRequest request,
			HttpServletResponse response) {

		String jsonText = "";

		try {

			// Finds all clients
			List<Client> allclients = clientFacade.findAll();

			ObjectMapper mapper = new ObjectMapper();
			jsonText = mapper.writeValueAsString(allclients);

			response.setStatus(HttpServletResponse.SC_OK);
			response.setContentType("application/json");

			// Check that the passwords match

		} catch (Throwable e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			jsonText = "{\"ERROR_CODE\":\"" + e.getMessage() + "\"}";
			// Set the exception and send it back to the caller

		} finally {
		}

		return jsonText;
	}

	/**
	 * Get Manager
	 * 
	 * @param jsonbody
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/getAllManagers")
	@ResponseBody
	public String getAllManagers(HttpServletRequest request,
			HttpServletResponse response) {

		String jsonText = "";

		try {

			// Finds all manager
			List<Manager> allmanager = managerFacade.findAll();

			ObjectMapper mapper = new ObjectMapper();
			jsonText = mapper.writeValueAsString(allmanager);

			response.setStatus(HttpServletResponse.SC_OK);
			response.setContentType("application/json");

			// Check that the passwords match

		} catch (Throwable e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			jsonText = "{\"ERROR_CODE\":\"" + e.getMessage() + "\"}";
			// Set the exception and send it back to the caller

		} finally {
		}

		return jsonText;
	}

	/**
	 * Get User Resources
	 * 
	 * @param jsonbody
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/userResources/{userId}/{type}")
	@ResponseBody
	public String getUserResource(@PathVariable("userId") String userId,
			@PathVariable("type") String resource_type,
			HttpServletRequest request, HttpServletResponse response) {

		System.out.println(userId + " ----  " + resource_type);
		String jsonText = "";

		ObjectMapper mapper = new ObjectMapper();

		try {

			// Finds the user by id
			Search searchCriteria = new Search();
			searchCriteria.addFilterEqual("userId", userId);
			User foundUser = userFacade.searchUnique(searchCriteria);
			if (foundUser == null) {
				response.sendError(HttpServletResponse.SC_BAD_REQUEST,
						"User Not Found id[ " + userId + "]");
				return "";
			}

			// Finds the user's resources
			searchCriteria = new Search();
			searchCriteria.addFilterEqual("groupId", foundUser.getGroupId());
			if (resource_type != null)
				searchCriteria.addFilterEqual("resourceType", resource_type);

			List<Resource> userResources = resourceFacade
					.search(searchCriteria);
			jsonText = mapper.writeValueAsString(userResources);

			response.setStatus(HttpServletResponse.SC_OK);
			response.setContentType("application/json");

		} catch (Throwable e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			response.setStatus(500);
			jsonText = "{\"ERROR_CODE\":\"" + e.getMessage() + "\"}";
			// Set the exception and send it back to the caller

		} finally {
		}

		return jsonText;
	}

	/**
	 * Create User
	 * 
	 * @param jsonbody
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/createUser")
	@ResponseBody
	public String createUser(@RequestBody String jsonbody,
			HttpServletRequest request, HttpServletResponse response) {

		String jsonText = "";

		try {

			// String jsonBody = IOUtils.toString( request.getInputStream());

			logger.debug("jsonbody:   \n" + jsonbody);

			ObjectMapper mapper = new ObjectMapper();
			User newUser = mapper.readValue(jsonbody, User.class);
			// encrypt the password
			PasswordService pwdService = new DefaultPasswordService();
			String hashedPassword = pwdService.encryptPassword(newUser
					.getPassword());

			newUser.setPassword(hashedPassword);
			newUser.setProfilePic("default.png");
			userFacade.save(newUser);

		} catch (Throwable e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			response.setStatus(500);
			jsonText = "{\"ERROR_CODE\":\"" + e.getMessage() + "\"}";
			// Set the exception and send it back to the caller

		} finally {
		}

		return jsonText;
	}

	/**
	 * Update User
	 * 
	 * @param jsonbody
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(method = RequestMethod.PUT, value = "/updateUser")
	@ResponseBody
	public String updateUser(@RequestBody String jsonbody,
			HttpServletRequest request, HttpServletResponse response) {

		String jsonText = "";

		try {

			logger.debug("jsonbody     :      \n" + jsonbody);

			ObjectMapper mapper = new ObjectMapper();
			User updateUser = mapper.readValue(jsonbody, User.class);

			updateUser.setPassword(new DefaultPasswordService()
					.encryptPassword(updateUser.getPassword()));
			// Finds the user by id
			Search searchCriteria = new Search();
			searchCriteria.addFilterEqual("userId", updateUser.getId());
			User foundUser = userFacade.searchUnique(searchCriteria);
			if (foundUser == null) {
				response.sendError(HttpServletResponse.SC_BAD_REQUEST,
						"User Not Found id[ " + updateUser.getId() + "]");
				return "";
			}

			userFacade.save(updateUser);

		} catch (Throwable e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			response.setStatus(404);
			jsonText = "{\"ERROR_CODE\":\"" + e.getMessage() + "\"}";
			// Set the exception and send it back to the caller

		} finally {
		}

		response.setStatus(HttpServletResponse.SC_OK);
		return jsonText;
	}

	/**
	 * Create Client
	 * 
	 * @param jsonbody
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/createClient")
	@ResponseBody
	public String createClient(@RequestBody String jsonbody,
			HttpServletRequest request, HttpServletResponse response) {

		String jsonText = "";

		try {

			// String jsonBody = IOUtils.toString( request.getInputStream());

			logger.debug("jsonbody:   \n" + jsonbody);

			ObjectMapper mapper = new ObjectMapper();
			Client obj = mapper.readValue(jsonbody, Client.class);

			String newId = RandomStringUtils.randomNumeric(6);
			obj.setClientId(Long.parseLong(newId));
			clientFacade.save(obj);

		} catch (Throwable e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			response.setStatus(500);
			jsonText = "{\"ERROR_CODE\":\"" + e.getMessage() + "\"}";
			// Set the exception and send it back to the caller

		} finally {
		}

		return jsonText;
	}

	/**
	 * Update Client
	 * 
	 * @param jsonbody
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(method = RequestMethod.PUT, value = "/updateClient")
	@ResponseBody
	public String updateClient(@RequestBody String jsonbody,
			HttpServletRequest request, HttpServletResponse response) {

		String jsonText = "";

		try {

			logger.debug("jsonbody     :      \n" + jsonbody);

			ObjectMapper mapper = new ObjectMapper();
			Client obj = mapper.readValue(jsonbody, Client.class);

			// Finds the user by id
			Search searchCriteria = new Search();
			searchCriteria.addFilterEqual("clientId", obj.getId());
			Client foundObj = clientFacade.searchUnique(searchCriteria);
			if (foundObj == null) {
				response.sendError(HttpServletResponse.SC_BAD_REQUEST,
						"User Not Found id[ " + obj.getId() + "]");
				return "";
			}

			clientFacade.save(obj);

		} catch (Throwable e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			response.setStatus(404);
			jsonText = "{\"ERROR_CODE\":\"" + e.getMessage() + "\"}";
			// Set the exception and send it back to the caller

		} finally {
		}

		response.setStatus(HttpServletResponse.SC_OK);
		return jsonText;
	}

	/**
	 * Create Manager
	 * 
	 * @param jsonbody
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/createManager")
	@ResponseBody
	public String createManager(@RequestBody String jsonbody,
			HttpServletRequest request, HttpServletResponse response) {

		String jsonText = "";

		try {

			// String jsonBody = IOUtils.toString( request.getInputStream());

			logger.debug("jsonbody:   \n" + jsonbody);

			ObjectMapper mapper = new ObjectMapper();
			Manager obj = mapper.readValue(jsonbody, Manager.class);

			String newId = RandomStringUtils.randomNumeric(6);
			obj.setId(Long.parseLong(newId));
			managerFacade.save(obj);

		} catch (Throwable e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			response.setStatus(500);
			jsonText = "{\"ERROR_CODE\":\"" + e.getMessage() + "\"}";
			// Set the exception and send it back to the caller

		} finally {
		}

		return jsonText;
	}

	/**
	 * Update Manager
	 * 
	 * @param jsonbody
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(method = RequestMethod.PUT, value = "/updateManager")
	@ResponseBody
	public String updateManager(@RequestBody String jsonbody,
			HttpServletRequest request, HttpServletResponse response) {

		String jsonText = "";

		try {

			logger.debug("jsonbody     :      \n" + jsonbody);

			ObjectMapper mapper = new ObjectMapper();
			Manager obj = mapper.readValue(jsonbody, Manager.class);

			// Finds the user by id
			Search searchCriteria = new Search();
			searchCriteria.addFilterEqual("managerId", obj.getId());
			Manager foundObj = managerFacade.searchUnique(searchCriteria);
			if (foundObj == null) {
				response.sendError(HttpServletResponse.SC_BAD_REQUEST,
						"User Not Found id[ " + obj.getId() + "]");
				return "";
			}

			managerFacade.save(obj);

		} catch (Throwable e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			response.setStatus(404);
			jsonText = "{\"ERROR_CODE\":\"" + e.getMessage() + "\"}";
			// Set the exception and send it back to the caller

		} finally {
		}

		response.setStatus(HttpServletResponse.SC_OK);
		return jsonText;
	}

	/**
	 * Add User to Group
	 * 
	 * @param jsonbody
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/addUserToGroup")
	@ResponseBody
	public String addUserToGroup(@RequestBody String jsonbody,
			HttpServletRequest request, HttpServletResponse response) {

		String jsonText = "";

		try {

			logger.debug("jsonbody     :      \n" + jsonbody);

			// UserDataTransferFacade userDTF =
			// (UserDataTransferFacade)ApplicationContextUtils.getContext().getBean("userDTF");
			// GroupDataTransferFacade groupDTF =
			// (GroupDataTransferFacade)ApplicationContextUtils.getContext().getBean("groupDTF");

			ObjectMapper mapper = new ObjectMapper();
			UserGroup newUserGroup = mapper
					.readValue(jsonbody, UserGroup.class);

			System.out.println("Saving user to group " + newUserGroup.getId()
					+ " : " + newUserGroup.getGroupId());

			/*
			 * User updateUser = mapper.readValue(jsonbody,User.class);
			 * 
			 * 
			 * 
			 * //Finds the user by id Search searchCriteria = new Search();
			 * searchCriteria.addFilterEqual("userId", updateUser.getUserId());
			 * User foundUser = userDTF.searchUnique(searchCriteria);
			 * if(foundUser == null){
			 * response.sendError(HttpServletResponse.SC_BAD_REQUEST,
			 * "User Not Found id[ " + updateUser.getUserId() + "]");
			 * hibernateSessionContext.rollbackTransaction(); return ""; }
			 * 
			 * //Finds the group by id searchCriteria = new Search();
			 * searchCriteria.addFilterEqual("groupId",
			 * updateUser.getGroupId()); Group foundGroup =
			 * groupDTF.searchUnique(searchCriteria); if(foundGroup == null){
			 * response.sendError(HttpServletResponse.SC_BAD_REQUEST,
			 * "Group r Not Found id[ " + updateUser.getGroupId() + "]");
			 * hibernateSessionContext.rollbackTransaction(); return ""; }
			 * 
			 * UserGroup newUserGroup = new UserGroup();
			 * newUserGroup.setGroupId(updateUser.getGroupId());
			 * newUserGroup.setUserId(updateUser.getUserId());
			 */
			userGroupFacade.save(newUserGroup);

		} catch (Throwable e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			response.setStatus(404);
			jsonText = "{\"ERROR_CODE\":\"" + e.getMessage() + "\"}";
			// Set the exception and send it back to the caller

		} finally {
		}

		response.setStatus(HttpServletResponse.SC_OK);
		return jsonText;
	}

	/**
	 * get User to Groups
	 * 
	 * @param jsonbody
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/userGroups/{userid}")
	@ResponseBody
	public String getUserGroups(@RequestBody String jsonbody,
			@PathVariable("userid") String userid, HttpServletRequest request,
			HttpServletResponse response) {

		String jsonText = "";

		try {

			logger.debug("jsonbody     :      \n" + jsonbody);

			ObjectMapper mapper = new ObjectMapper();

			// Finds the user by id
			Search searchCriteria = new Search();
			searchCriteria.addFilterEqual("userId", userid);
			User foundUser = userFacade.searchUnique(searchCriteria);
			if (foundUser == null) {
				response.sendError(HttpServletResponse.SC_BAD_REQUEST,
						"User Not Found id[ " + userid + "]");
				return "";
			}

			searchCriteria = new Search();
			searchCriteria.addFilterEqual("userId", userid);
			List<UserGroup> userGroupList = userGroupFacade
					.search(searchCriteria);

			jsonText = mapper.writeValueAsString(userGroupList);

		} catch (Throwable e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			response.setStatus(404);
			jsonText = "{\"ERROR_CODE\":\"" + e.getMessage() + "\"}";
			// Set the exception and send it back to the caller

		} finally {
		}

		response.setStatus(HttpServletResponse.SC_OK);
		return jsonText;
	}

	/**
	 * Create Group
	 * 
	 * @param jsonbody
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/createGroup")
	@ResponseBody
	public String createGroup(@RequestBody String jsonbody,
			HttpServletRequest request, HttpServletResponse response) {

		String jsonText = "";

		try {

			// String jsonBody = IOUtils.toString( request.getInputStream());

			logger.debug("jsonbody:   \n" + jsonbody);

			ObjectMapper mapper = new ObjectMapper();
			Group newGroup = mapper.readValue(jsonbody, Group.class);

			System.out
					.println("Group Objct Server ----------------------------"
							+ newGroup);

			groupFacade.save(newGroup);

		} catch (Throwable e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			response.setStatus(500);
			jsonText = "{\"ERROR_CODE\":\"" + e.getMessage() + "\"}";
			// Set the exception and send it back to the caller

		} finally {
		}

		return jsonText;
	}

	/**
	 * get Group
	 * 
	 * @param jsonbody
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/getGroup/{groupid}")
	@ResponseBody
	public String getGroup(@RequestBody String jsonbody,
			@PathVariable("groupid") String groupid,
			HttpServletRequest request, HttpServletResponse response) {

		String jsonText = "";

		try {

			// String jsonBody = IOUtils.toString( request.getInputStream());

			logger.debug("jsonbody:   \n" + jsonbody);

			// Finds the group by id
			Search searchCriteria = new Search();
			searchCriteria.addFilterEqual("groupId", groupid);
			Group foundGroup = groupFacade.searchUnique(searchCriteria);
			if (foundGroup == null) {
				response.sendError(HttpServletResponse.SC_BAD_REQUEST,
						"Group forr Not Found id[ " + groupid + "]");
				return "";
			}
			ObjectMapper mapper = new ObjectMapper();
			jsonText = mapper.writeValueAsString(foundGroup);

			response.setStatus(HttpServletResponse.SC_OK);
			response.setContentType("application/json");

		} catch (Throwable e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			response.setStatus(500);
			jsonText = "{\"ERROR_CODE\":\"" + e.getMessage() + "\"}";
			// Set the exception and send it back to the caller

		} finally {
		}

		return jsonText;
	}

	/**
	 * Create Group
	 * 
	 * @param jsonbody
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/createResource")
	@ResponseBody
	public String createResource(@RequestBody String jsonbody,
			HttpServletRequest request, HttpServletResponse response) {

		String jsonText = "";

		try {

			logger.debug("jsonbody:   \n" + jsonbody);

			ObjectMapper mapper = new ObjectMapper();
			Resource newResource = mapper.readValue(jsonbody, Resource.class);
			resourceFacade.save(newResource);

		} catch (Throwable e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			response.setStatus(500);
			jsonText = "{\"ERROR_CODE\":\"" + e.getMessage() + "\"}";
			// Set the exception and send it back to the caller

		} finally {
		}

		return jsonText;
	}

	/**
	 * get Resource
	 * 
	 * @param jsonbody
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/getResource/{resourceid}")
	@ResponseBody
	public String getResource(@RequestBody String jsonbody,
			@PathVariable("resourceid") String resourceid,
			HttpServletRequest request, HttpServletResponse response) {

		String jsonText = "";

		try {

			// String jsonBody = IOUtils.toString( request.getInputStream());

			logger.debug("jsonbody:   \n" + jsonbody);

			// Finds the group by id
			Search searchCriteria = new Search();
			searchCriteria.addFilterEqual("resourceId", resourceid);
			Resource foundResource = resourceFacade
					.searchUnique(searchCriteria);
			if (foundResource == null) {
				response.sendError(HttpServletResponse.SC_BAD_REQUEST,
						"Resource Not Found id[ " + resourceid + "]");
				return "";
			}
			ObjectMapper mapper = new ObjectMapper();
			jsonText = mapper.writeValueAsString(foundResource);

			response.setStatus(HttpServletResponse.SC_OK);
			response.setContentType("application/json");

		} catch (Throwable e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			response.setStatus(500);
			jsonText = "{\"ERROR_CODE\":\"" + e.getMessage() + "\"}";
			// Set the exception and send it back to the caller

		} finally {
		}

		return jsonText;
	}

	/**
	 * Get Resource
	 * 
	 * @param jsonbody
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/getAllResources")
	@ResponseBody
	public String getAllResource(HttpServletRequest request,
			HttpServletResponse response) {

		String jsonText = "";

		try {

			// Finds all users
			List<Resource> allResource = resourceFacade.findAll();

			ObjectMapper mapper = new ObjectMapper();
			jsonText = mapper.writeValueAsString(allResource);

			response.setStatus(HttpServletResponse.SC_OK);
			response.setContentType("application/json");

			// Check that the passwords match

		} catch (Throwable e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			jsonText = "{\"ERROR_CODE\":\"" + e.getMessage() + "\"}";
			// Set the exception and send it back to the caller

		} finally {
		}

		return jsonText;
	}

	/**
	 * Get Report
	 * 
	 * @param jsonbody
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/getAllReports")
	@ResponseBody
	public String getAllReport(HttpServletRequest request,
			HttpServletResponse response) {

		String jsonText = "";

		try {

			List<Report> allResource = reportFacade.findAll();

			ObjectMapper mapper = new ObjectMapper();
			jsonText = mapper.writeValueAsString(allResource);

			response.setStatus(HttpServletResponse.SC_OK);
			response.setContentType("application/json");

			// Check that the passwords match

		} catch (Throwable e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			jsonText = "{\"ERROR_CODE\":\"" + e.getMessage() + "\"}";
			// Set the exception and send it back to the caller

		} finally {
		}

		return jsonText;
	}

	/**
	 * Get User-Groups
	 * 
	 * @param jsonbody
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/getAllUserGroups")
	@ResponseBody
	public String getAllUserGroups(HttpServletRequest request,
			HttpServletResponse response) {

		String jsonText = "";

		try {

			// Finds all users
			List<UserGroup> allUserGroups = userGroupFacade.findAll();

			ObjectMapper mapper = new ObjectMapper();
			jsonText = mapper.writeValueAsString(allUserGroups);

			response.setStatus(HttpServletResponse.SC_OK);
			response.setContentType("application/json");

		} catch (Throwable e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			jsonText = "{\"ERROR_CODE\":\"" + e.getMessage() + "\"}";
			// Set the exception and send it back to the caller

		} finally {
		}

		return jsonText;
	}

	/**
	 * Get Groups
	 * 
	 * @param jsonbody
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/getAllGroups")
	@ResponseBody
	public String getAllGroups(HttpServletRequest request,
			HttpServletResponse response) {

		String jsonText = "";

		try {

			// Finds all users
			List<Group> allGroups = groupFacade.findAll();

			ObjectMapper mapper = new ObjectMapper();
			jsonText = mapper.writeValueAsString(allGroups);

			response.setStatus(HttpServletResponse.SC_OK);
			response.setContentType("application/json");

		} catch (Throwable e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			jsonText = "{\"ERROR_CODE\":\"" + e.getMessage() + "\"}";
			// Set the exception and send it back to the caller

		} finally {
		}

		return jsonText;
	}

	/**
	 * 
	 * Update Group
	 * 
	 * @param jsonbody
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(method = RequestMethod.PUT, value = "/updateGroup")
	@ResponseBody
	public String updateGroup(@RequestBody String jsonbody,
			HttpServletRequest request, HttpServletResponse response) {
		String jsonText = "";
		try {
			logger.debug("jsonbody:   \n" + jsonbody);
			ObjectMapper mapper = new ObjectMapper();
			Group newGroup = mapper.readValue(jsonbody, Group.class);
			groupFacade.save(newGroup);
		} catch (Throwable e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			response.setStatus(500);
			jsonText = "{\"ERROR_CODE\":\"" + e.getMessage() + "\"}";
			// Set the exception and send it back to the caller
		} finally {
		}
		return jsonText;
	}

	/**
	 * 
	 * Update Group
	 * 
	 * @param jsonbody
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(method = RequestMethod.PUT, value = "/updateResource")
	@ResponseBody
	public String updateResource(@RequestBody String jsonbody,
			HttpServletRequest request, HttpServletResponse response) {
		String jsonText = "";
		try {
			logger.debug("jsonbody:   \n" + jsonbody);
			ObjectMapper mapper = new ObjectMapper();
			Resource newResource = mapper.readValue(jsonbody, Resource.class);
			resourceFacade.save(newResource);
		} catch (Throwable e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			response.setStatus(500);
			jsonText = "{\"ERROR_CODE\":\"" + e.getMessage() + "\"}";
			// Set the exception and send it back to the caller
		} finally {
		}
		return jsonText;
	}

	/**
	 * Upload user Profile Pic
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/uploadProfilePic", method = RequestMethod.POST)
	public @ResponseBody
	String store(HttpServletRequest request, HttpServletResponse response,
			@RequestParam("file") MultipartFile file) {

		String jsonText = "";

		// THIS IS A HACK for the explicit use of the DEMO we will fix this with
		// proper system properties in the configuration and remove the hard
		// code location
		// String storeLocation =
		// "C:\\Program Files (x86)\\Apache Software Foundation\\Tomcat 7.0\\webapps";

		// ADJUST to store in sample place CHRIS

		// ################################################################################################
		try {

			User userObj = (User) request.getSession().getAttribute("user");
			String fileName = userObj.getId() + "-"
					+ file.getOriginalFilename();
			userObj.setProfilePic(fileName);

			// Saving file at server location
			String storeLocation = request.getServletContext().getRealPath(
					"/assets/images/");

			String fullFileName = storeLocation + "\\" + fileName;
			System.out.println("Uploaded file name : " + fullFileName);
			File reportFileToStore = new File(fullFileName);

			FileOutputStream fileOutputStream = new FileOutputStream(
					reportFileToStore);
			IOUtils.copy(file.getInputStream(), fileOutputStream);
			fileOutputStream.close();

			userFacade.save(userObj);

			String referrer = request.getHeader("referer");

			response.sendRedirect(referrer);

		} catch (Throwable e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			response.setStatus(500);
			jsonText = "{\"ERROR_CODE\":\"" + e.getMessage() + "\"}";
			// Set the exception and send it back to the caller

		} finally {
		}
		return "";
	}

	// User preference Start

	/**
	 * Save UserPreference
	 * 
	 * @param jsonbody
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/saveUserPreference")
	@ResponseBody
	public String saveUserPreference(@RequestBody String jsonbody,
			HttpServletRequest request, HttpServletResponse response) {
		String jsonText = "";
		try {
			ObjectMapper mapper = new ObjectMapper();

			UserPreference userPreference = mapper.readValue(jsonbody,
					UserPreference.class);
			String newId = RandomStringUtils.randomNumeric(6);
			userPreference.setPreferenceId(Long.parseLong(newId));
			userPreference.setCreatedOn(new Date());
			userPreference.setUpdatedOn(new Date());
			System.out.println("User Prefrence Object >>---------------"
					+ userPreference);

			// Loop to save user preference one by one
			userPrefFacade.save(userPreference);
			jsonText = "Success";
		} catch (Throwable e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			response.setStatus(500);
			jsonText = "{\"ERROR_CODE\":\"" + e.getMessage() + "\"}";
			// Set the exception and send it back to the caller
		} finally {
		}
		return jsonText;
	}

	// End

}
